#!/bin/bash

sed_escape() {
	echo "$1" | sed -e 's/\(\/\|\\\|&\)/\\&/g'
}

if [ "$1" = "--help" ]; then
	echo "kernel module repsitory generator"
	exit 1
fi

OUTDIR="$1"
URL="$2"

set -e
shopt -s nullglob

[[ ${URL} =~ ^kmod://(.*)$ ]]
PKGDIR="${BASH_REMATCH[1]}"

KERNELS=""

if [ -d /lib/modules ]; then
	cd /lib/modules
	for ver in *; do
		if [ -d "${ver}" ] && [ -d "${ver}/source" ] && [ -d "${ver}/build" ]; then
			KERNELS="${KERNELS} ${ver}"
		fi
	done
fi

rm -rf "${OUTDIR}"

mkdir -p "${OUTDIR}"/{profiles,metadata}
echo "kmod" > "${OUTDIR}/profiles/repo_name"
echo "masters = gentoo ambro" > "${OUTDIR}/metadata/layout.conf"

cd "${PKGDIR}"

if [ -d "${PKGDIR}/eclass" ]; then
	cp -r "${PKGDIR}/eclass" "${OUTDIR}/"
fi

if [ -f "${PKGDIR}/profiles/categories" ]; then
	cp "${PKGDIR}/profiles/categories" "${OUTDIR}/profiles/"
fi

calc_hash() {
	local type=$1
	local file=$2
	cat "${file}" | openssl dgst -${type} -r | cut -d ' ' -f1
}

make_manifest() {
	local srcman=$1
	local dstdir=$2

	local outman="${dstdir}/Manifest"
	echo -n > "${outman}"

	local LINE
	while read LINE; do
		[[ $LINE =~ ^EBUILD ]] && continue
		echo "${LINE}" >> "${outman}"
	done < "${srcman}"

	local f
	for f in "${dstdir}"/*.ebuild; do
		local name=$(basename "${f}")
		local size=$(stat -c '%s' "${f}")
		local h_ripemd160=$(calc_hash ripemd160 "${f}")
		local h_sha1=$(calc_hash sha1 "${f}")
		local h_sha256=$(calc_hash sha256 "${f}")
		echo "EBUILD ${name} ${size} RMD160 ${h_ripemd160} SHA1 ${h_sha1} SHA256 ${h_sha256}" >> "${outman}"
	done
}

for cat in *; do
	[ -d "${PKGDIR}/${cat}" ] || continue
	cd "${PKGDIR}/${cat}"
	for name in *; do
		[ -d "${PKGDIR}/${cat}/${name}" ] || continue
		cd "${PKGDIR}/${cat}/${name}"
		for kernel in $KERNELS; do
			namever=$(echo "$kernel" | sed 's/\./-/g')
        		pname="${name}-${namever}-x"
        		dir="${OUTDIR}/${cat}/${pname}"
			mkdir -p "${dir}"
			if [ -d files ]; then
				cp -r files "${dir}/"
			fi

			replace_kernel=$(sed_escape "${kernel}")
			for f in *; do
				if [[ $f =~ ${name}-(.*)\.ebuild ]]; then
					version="${BASH_REMATCH[1]}"
					cat "${f}" | sed 's/<<KERNEL>>/'"${replace_kernel}"'/g' > "${dir}/${pname}-${version}.ebuild"
				fi
			done

			make_manifest Manifest "${dir}"
		done
	done
done
